/**  
 * Copyrights@2006, Tianyuan DIC Information Co.,Ltd.
 * 文件名:    TMallRetTask.java  
 * 描述:   
 * 作者:     kaiyang
 * 版本:    1.0  
 * 创建时间:   2015年6月12日 下午3:09:33  
 *  
 * 修改历史:  
 * 日期                          作者           版本         描述  
 * ------------------------------------------------------------------  
 * 2015年6月12日      kaiyang      1.0        1.0 Version  
 */ 
package com.hp.bon.sgw.wh.channel.handler;

import com.hp.bon.sgw.wh.bean.tmall.TmallFluxBean;
import com.hp.bon.sgw.wh.service.TmallLogDao;
import com.hp.bon.sgw.wh.utils.SignUtilsImpl;
import org.apache.axis.client.Call;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;

/**  
 * @ClassName: TMallRetTask   
 * @Description: TODO  
 * @author: kaiyang  
 * @date:2015年6月12日 下午3:09:33     
 */
public class TmallFlowTask implements Runnable{
	private final static Logger _log = LoggerFactory.getLogger(TmallFlowTask.class);
	private TmallFluxBean tmallFluxBean;
//	private TmallLogDao tmallLogDao;
	private Call call;
	private Call call1;
	private Integer HomeAreaCode; 
	private String pubKeyValue; 
	
	public TmallFlowTask(TmallFluxBean tmallFluxBean,
			TmallLogDao tmallLogDao,
			Call call, Call call1,Integer HomeAreaCode,String pubKeyValue) {
//		this.tmallLogDao = tmallLogDao;
		this.call = call;
        this.call1 = call1;
        this.tmallFluxBean = tmallFluxBean;
        this.HomeAreaCode = HomeAreaCode;
        this.pubKeyValue = pubKeyValue;
	}

	@Override
	public void run() {
		
		
		try {
			
		Map<String,String> data = new HashMap<String, String>();
		String sn =Complement(tmallFluxBean.getCapInstId())+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+getRandomCode();
		
		StringBuffer sb =new StringBuffer();
		sb.append("<?xml version='1.0' encoding='UTF-8'?>");
		sb.append("<interfaceRoot>");
		sb.append("<transactionId>" + sn + "</transactionId>");
		sb.append("<busiTranId>" + sn + "</busiTranId>");
		sb.append("<appId>" + tmallFluxBean.getAppId() + "</appId>");
		sb.append("<channelId>" + tmallFluxBean.getChannelId() + "</channelId>");
		sb.append("<signCode>" + tmallFluxBean.getSignCode() + "</signCode>");
		sb.append("<capInstId>" + tmallFluxBean.getCapInstId() + "</capInstId>");
		sb.append("<encryptCode></encryptCode> ");
		sb.append("<rtnDataFormatType>XML</rtnDataFormatType>");
		sb.append("<contentList>");
		sb.append("<content type='CHK_PRICE_ORDER'>");
		sb.append("<contentId>1</contentId>");
		sb.append("<regionId>" + HomeAreaCode + "</regionId>");
		sb.append("<staffId>" + tmallFluxBean.getStaffId() + "</staffId>");
		sb.append("<staffCode>" + tmallFluxBean.getStaffCode() + "</staffCode>");
		sb.append("<operInfo>");
		sb.append("<accNbr>" + tmallFluxBean.getAccountVal() + "</accNbr>");
		if(HomeAreaCode!=1001){
			sb.append("<pricePlanId>" + tmallFluxBean.getSpuIdValue() + "</pricePlanId>");
		}else{
			sb.append("<pricePlanId>" + tmallFluxBean.getSpuIdValueWH() + "</pricePlanId>");
		}
		
		sb.append("<actionType>A</actionType>");
		sb.append("</operInfo>");
		sb.append("</content></contentList></interfaceRoot>");
		
		_log.info("校验 = {}",sb.toString());
		
		String reslut;
		
		reslut = (String)call.invoke(new Object[] { sb.toString() });
		
		
		_log.info("校验结果= {}",reslut);
		Map<String,Object> reslutData =xmlStrToMap(reslut);
		_log.info("校验结果= {}",reslutData.get("returnType").toString());
		if("0".equals(reslutData.get("returnType"))){//成功
			
			_log.info("校验结果= {}","成功");
			sb.delete(0,sb.length());
			sb.append("<?xml version='1.0' encoding='UTF-8'?>");
			sb.append("<interfaceRoot>");
			sb.append("<transactionId>" + sn + "</transactionId>");
			sb.append("<busiTranId>" + sn + "</busiTranId>");
			sb.append("<appId>" + tmallFluxBean.getAppId1() + "</appId>");
			sb.append("<channelId>" + tmallFluxBean.getChannelId1() + "</channelId>");
			sb.append("<signCode>" + tmallFluxBean.getSignCode1() + "</signCode>");
			sb.append("<capInstId>" + tmallFluxBean.getCapInstId1() + "</capInstId>");
			sb.append("<encryptCode></encryptCode> ");
			sb.append("<rtnDataFormatType>XML</rtnDataFormatType>");
			sb.append("<contentList>");
			sb.append("<content type='SAVE_PRICE_ORDER'>");
			sb.append("<contentId>1</contentId>");
			sb.append("<regionId>" + HomeAreaCode + "</regionId>");
			sb.append("<staffId>" + tmallFluxBean.getStaffId() + "</staffId>");
			sb.append("<staffCode>" + tmallFluxBean.getStaffCode() + "</staffCode>");
			sb.append("<operInfo>");
			sb.append("<accNbr>" + tmallFluxBean.getAccountVal() + "</accNbr>");
			if(HomeAreaCode!=1001){
				sb.append("<pricePlanId>" + tmallFluxBean.getSpuIdValue() + "</pricePlanId>");
			}else{
				sb.append("<pricePlanId>" + tmallFluxBean.getSpuIdValueWH() + "</pricePlanId>");
			}
			sb.append("<actionType>A</actionType>");
			sb.append("</operInfo>");
			sb.append("</content></contentList></interfaceRoot>");
			
			_log.info("流量购买 = {}",sb.toString());
			reslut =(String)call1.invoke(new Object[] { sb.toString() });
			
			_log.info("校验结果= {}",reslut);
			
			reslutData =xmlStrToMap(reslut);
			if("0".equals(reslutData.get("returnType"))){//成功
				_log.info("购买流量成功= {}",reslut);
				data.put("coopOrderNo",reslutData.get("SalesIndentId").toString());
				data.put("coopOrderStatus","UNDERWAY");
				data.put("errCode","");
				data.put("errDesc","");
			}else{
				_log.info("购买流量失败= {}",reslut);
				data.put("coopOrderNo","");
				data.put("coopOrderStatus","UNDERWAY");
				data.put("errCode","");
				data.put("errDesc","");
			}
			
		}else{//校验失败
			_log.info("校验结果= {}","校验失败");
			
			data.put("coopOrderNo","");
			data.put("coopOrderStatus","UNDERWAY");
			data.put("errCode","");
			data.put("errDesc","");
		}
		
//		TmallFluxLog tmallFluxLog =new TmallFluxLog();
//		tmallFluxLog.setTbOrderNo(tmallFluxBean.getTbOrderNo());
//		if(reslutData.get("SalesIndentId")!=null){
//			tmallFluxLog.setSalesIndentId(reslutData.get("SalesIndentId").toString());
//		}
//		if(reslutData.get("CustIndentNbr")!=null){
//			tmallFluxLog.setCustIndentNbr(reslutData.get("CustIndentNbr").toString());
//		}
//		tmallFluxLog.setFlag(Integer.valueOf(reslutData.get("returnType").toString()));
//
//		tmallLogDao.updateTmallFluxLog(tmallFluxLog);
		
		TreeMap<String,String> paraMap = new TreeMap<String, String>();
		
		String coopOrderNo = data.get("coopOrderNo");
		String errDesc = data.get("errDesc");
		
		_log.info("request tbOrderNo:{}",tmallFluxBean.getTbOrderNo());
		paraMap.put("tbOrderNo", tmallFluxBean.getTbOrderNo());
		paraMap.put("bizType", tmallFluxBean.getBizType());
		if(coopOrderNo!=null&&!"".equals(coopOrderNo)){
			paraMap.put("coopOrderNo", coopOrderNo);
		}else{
			paraMap.put("coopOrderNo", tmallFluxBean.getTbOrderNo());
		}
		
		paraMap.put("supplierId", tmallFluxBean.getSupplierId());
		
		paraMap.put("failDesc",errDesc);
		paraMap.put("ts", System.currentTimeMillis()+"");
		
		if (reslutData.get("SalesIndentId")!=null)
		{
			paraMap.put("coopOrderStatus", "SUCCESS");
			paraMap.put("failCode","");
		}
		else 
		{
			paraMap.put("coopOrderStatus", "FAILED");
			paraMap.put("failCode","0414");
		}
		String source = "";
		for(Entry<String,String> entry:paraMap.entrySet())
		{
			if(entry.getValue()!=null&&!"".equals(entry.getValue())){
			source += entry.getKey()+entry.getValue();
			}
		}
		source = source + pubKeyValue;
		String sign = SignUtilsImpl.getTmallSign(source);
		paraMap.put("sign",sign);
		
		
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		for(Entry<String,String> entry:paraMap.entrySet())
		{
			BasicNameValuePair pair = new BasicNameValuePair(entry.getKey(),entry.getValue());
			params.add(pair);
		}
		String getParam = URLEncodedUtils.format(params,"GBK");
		_log.info("request param:{}",getParam);
		_log.info("retUrl:"+tmallFluxBean.getNotifyUrl());
		HttpGet httpGet = new HttpGet(tmallFluxBean.getNotifyUrl()+"?"+getParam);
		HttpClient httpClient = new DefaultHttpClient();
		HttpResponse httpResponse = httpClient.execute(httpGet);
		_log.info("response http code = {}",httpResponse.getStatusLine().getStatusCode());
		_log.info("response Data = {}",EntityUtils.toString(httpResponse.getEntity(),"UTF-8"));
		}catch(Exception e){
			_log.info("异步任务异常 = {}",e.getMessage());
		}
	}
	
	
	private String getRandomCode(){
		Random random = new Random();
		String result="";
		for(int i=0;i<4;i++){
			result+=random.nextInt(10);
		}
		System.out.println(result);
		return result;
	}
	
    /** 
     * 将xml格式的字符串转换成Map对象 
     *  
     * @param xmlStr xml格式的字符串 
     * @return Map对象 
     * @throws Exception 异常 
     */  
    public  static Map<String, Object> xmlStrToMap(String xmlStr) throws Exception {  
        Map<String, Object> map = new HashMap<String, Object>();  
        //将xml格式的字符串转换成Document对象  
        Document doc = DocumentHelper.parseText(xmlStr);  
        //获取根节点  
        Element root = doc.getRootElement();  
        //获取根节点下的所有元素  
        List children = root.elements();  
        //循环所有子元素  
        if(children != null && children.size() > 0) {  
            for(int i = 0; i < children.size(); i++) {  
                Element child = (Element)children.get(i);  
                map.put(child.getName(), child.getTextTrim()); 
                if(child.getName().equals("returnList")){
                	for(int j = 0; j < child.elements().size(); j++) { 
                		Element child1 = (Element)child.elements().get(j);  
                		map.put(child1.getName(), child1.getTextTrim()); 
                		for(int k = 0; k < child1.elements().size(); k++) { 
                			Element child2 = (Element)child1.elements().get(k);
                			map.put(child2.getName(), child2.getTextTrim()); 
                			if(child2.getName().equals("returnMessage")){
                				for(int n = 0; n < child2.elements().size(); n++) { 
                					Element child3 = (Element)child2.elements().get(n);
                					map.put(child3.getName(), child3.getTextTrim()); 
                				}
                			}
                		}
                	}
                }else if(child.getName().equals("return_info")){
                	for(int j = 0; j < child.elements().size(); j++) { 
                		Element child1 = (Element)child.elements().get(j);  
                		map.put(child1.getName(), child1.getTextTrim()); 
                	}
                }
            }  
        }  
        return map;  
    }
    
    
	private String Complement(String str)
    {
		for (int j = str.length(); j<13 ; j++) {
			str+="0";
		}
		return str;
    }

}
